<template>
  <div class="page search-page">
    <div class="handlePart">
      <el-form :inline="true" :model="form">
        <el-form-item label="站点名称：">
          <el-select
            size="small"
            v-model="form.hydroStationId"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in jclxOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监测时间：">
          <el-date-picker
            size="small"
            v-model="monthRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            format="yyyy-MM"
            value-format="yyyy-MM"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            size="small"
            type="warning"
            icon="el-icon-clear"
            @click="clear"
            >清空</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="search"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="success"
            icon="el-icon-download"
            @click="exportExcel"
            >数据导出</el-button
          >
        </el-form-item>
        <el-form-item style="float: right">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            @click="add"
            >新增</el-button
          >
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="dels"
            >删除</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div v-show="activeName == '网格视图'">
      <div class="tablePart">
        <el-table
          ref="listTable"
          :data="list"
          :height="'calc(100vh - 290px)'"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="55"
          ></el-table-column>
          <el-table-column
            prop="hydroStationName"
            label="站点名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="waterAmount"
            label="水量值"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="date"
            label="监测日期(年月)"
            align="center"
          ></el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="160"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-edit"
                title="编辑"
                @click="edit(scope.row)"
              ></el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                title="删除"
                @click="del(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagePart">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div class="chart" v-show="activeName == '图像视图'">
      <div id="myChart" class="chartDiv"></div>
    </div>
    <el-radio-group v-model="activeName" class="tab-group">
      <el-radio-button label="网格视图"></el-radio-button>
      <el-radio-button label="图像视图"></el-radio-button>
    </el-radio-group>
    <EditDialog ref="editDialogRef" @listInit="listInit" />
  </div>
</template>
<script>
import EditDialog from "./editDialog.vue";
// import DetailDialog from './detailDialog.vue';
export default {
  data() {
    return {
      form: {
        keywords: "",
        hydroStationId: "",
        dateBegin: "",
        dateEnd: "",
        orderBy: "date",
      },
      activeName: "网格视图",
      monthRange: [],
      list: [],
      jclx: [],
      jclxOptions: [],
      isVisible: true,
      page: 1,
      size: 10,
      total: 0,
      selectList: [],
    };
  },
  created() {},
  async mounted() {
    //this.getparams();
    await this.getparams();
    this.listInit();
    this.chartInit();
  },
  methods: {
    async getparams() {
      let res = await this.$api.getHasWaterstationName({
        keywords: this.keywords,
      });
      if (res && res.code == 200) {
        this.jclxOptions = res.data || [];
        this.form.hydroStationId = this.jclxOptions[0].id;
      }
    },
    listInit() {
      if (this.monthRange && this.monthRange.length) {
        this.form.dateBegin = this.monthRange[0];
        this.form.dateEnd = this.monthRange[1];
      } else {
        this.form.dateBegin = "";
        this.form.dateEnd = "";
      }
      let params = Object.assign({}, this.form, {
        size: this.size,
        page: this.page,
        orderBy: "date",
      });
      this.$api.getWaterMonitorList(params).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || {};
          this.total = data.total || 0;
          this.list = [] = data.list || [];
        }
      });
    },
    //清空
    clear() {
      this.monthRange = [];
      this.end = "";
      this.start = "";
      this.keywords = "";
      //this.form.hydroStationId = this.jclxOptions[0].id;
      Object.assign(this.form, this.$options.data().form);
      this.listInit();
      this.chartInit();
    },
    // 查询
    search() {
      this.page = 1;
      if(this.form.hydroStationId == ''){
        this.$notify.warning({
          title: '警告',
          message: '请选择站点名称！'
        });
        return
      }
      this.listInit();
      this.chartInit();
    },
    async exportExcel() {
      if (this.monthRange && this.monthRange.length) {
        this.form.dateBegin = this.monthRange[0];
        this.form.dateEnd = this.monthRange[1];
      } else {
        this.form.dateBegin = "";
        this.form.dateEnd = "";
      }
      let params = Object.assign({},this.form,{
        size: 99999,
        page: 1,
        orderBy: "date"
      })
      const allRes = await this.$api.getWaterMonitorList(params);
      if (allRes && allRes.code === 200) {
        const data = allRes.data.list || [];
        const tableRef = this.$refs.listTable;
        this.$exportExcel(data, tableRef, "水文站水量监测");
      } else {
        this.$message.error("获取数据失败");
      }
    },
    // 新增
    add() {
      this.$refs.editDialogRef.showModal("add");
    },
    // 编辑
    edit(row) {
      this.$refs.editDialogRef.showModal("edit", row);
    },
    // 配置
    config(row) {
      // this.$refs.detailDialogRef.showModal(row);
    },
    // 删除
    del(row) {
      this.$confirm("数据删除后将无法恢复，确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.delWaterMonitor([row.id]).then((res) => {
            if (res && res.code == 200) {
              this.$notify.success({
                title: "成功",
                message: "删除成功!",
              });
              this.listInit();
            }
          });
        })
        .catch(() => {});
    },
    // 批量删除
    dels() {
      if (this.selectList.length == 0) {
        this.$notify.warning({
          title: "警告",
          message: "请至少选择一条数据！",
        });
        return;
      }
      let ids = [];
      this.selectList.forEach((l) => {
        ids.push(l.id);
      });
      this.$confirm("数据删除后将无法恢复，确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.delWaterMonitor(ids).then((res) => {
            if (res && res.code == 200) {
              this.$notify.success({
                title: "成功",
                message: "删除成功!",
              });
              this.listInit();
            }
          });
        })
        .catch(() => {});
    },
    // 多选
    handleSelectionChange(val) {
      this.selectList = val;
    },
    // size change
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.listInit();
    },
    // page change
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.listInit();
    },
    ridioChange() {
      if (this.activeName == "图像视图") {
        this.form.level = "10";
      }
    },
    chartInit() {
      if (this.monthRange && this.monthRange.length) {
        this.form.dateBegin = this.monthRange[0];
        this.form.dateEnd = this.monthRange[1];
      } else {
        this.form.dateBegin = "";
        this.form.dateEnd = "";
      }
      let params = Object.assign({}, this.form, {
        size: 0,
        page: 0,
        orderBy: "date",
      });
      this.$api.getAllWaterMonitorList(params).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || [];
          let xAxisData = [];
          let serieData = [];
          data.forEach((l) => {
            l.date = l.date
              ? l.date
              : "";
            xAxisData.push(l.date);
            serieData.push(l.waterAmount);
          });
          this.getChartInit(xAxisData, serieData);
        }
      });
    },
    getChartInit(xAxisData, serie1Data) {
      let item1 = {
        name: "水量值",
        type: "line",
        smooth: true,
        barMaxWidth: "60",
        // areaStyle: {},
        emphasis: {
          focus: "series",
        },
        color: ["#3398db"],
        data: serie1Data,
      };

      let legendData = ["水量值"];
      let series = [item1];
      let myChart = this.$echarts.init(document.getElementById("myChart"));
      let option = {
        title: {
          text: "水量值变化趋势",
        },
        tooltip: {
          trigger: "axis",
          formatter: function(params) {
            return `<div>日期: ${params[0].name}</div><div>水量值: ${params[0].value}</div>`;
          }
        },
        legend: {
          data: legendData,
        },
        toolbox: {
          show: true,
          feature: {
            restore: {},
            saveAsImage: {},
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xAxisData,
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
          },
        ],
        yAxis: {
          type: "value",
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
            },
          },
        },
        series: series,
      };
      option && myChart.setOption(option);

      let _this = this;
      // 监听toolbox中的事件
      /* myChart.on('magictypechanged', function (params) {
         console.log(params)
         _this.form.chartType = params.currentType == 'line' ? '折线图' : '柱状图'
         _this.chartInit()

       });*/

      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },
  },
  components: { EditDialog },
};
</script>

<style lang="less" scoped>
.page.search-page {
  position: relative;


  .chart {
    width: calc(100% - 20px);
    height: calc(100% - 80px);
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .chartDiv {
    width: calc(100vw - 20px);
    height:calc(100vh - 290px);
  }

  .tab-group {
    position: absolute;
    bottom: 10px;
    left: 10px;
  }
}
</style>
